<template>
  <van-list class="home" v-model="loading" :finished="finished"  @load="onLoad" :immediate-check="false">
    <div class="list-left">
      <van-sticky >
        <van-sidebar style="width:100%; position: fixed"
                   v-model="activeIndex" @change="onSidebarChange">
          <van-sidebar-item
              v-for="(item, index) in sidebarItems"
              :key="index"
              :title="item.title"
          />
      </van-sidebar>
      </van-sticky>
    </div>
    <div class="list-right" ref="listRight" @scroll="onScroll" >
      <van-tabs v-model="activeTab" style="width: 100%;" sticky
                offset-top="90px" shrink :color="'rgb(38, 184, 245)'">
        <van-tab  style="display:flex;flex-direction: column;justify-content: center; align-items: center"
                 v-for="tab in FOOD_TAB" :title="tab.title">
          <div v-for="(v,index) in FoodList" :key="v.foodId" style="width:90%;overflow-y:auto" :id="`category-${index}`">
            <van-card>
            <template #title>
              <div style="font-size: 3.5vw;font-weight: bold">
                {{v.foodName}}
              </div>
              <br>
            </template>
            <template #desc>
              <div style="font-style: italic">
                {{v.foodExplain}}
              </div>
            </template>
            <!-- 自定义价格 -->
            <template #price>
              <span style="font-size:0.8rem;color: rgb(182,63,72)">￥</span>
              <span style="font-size: 2vh;color: rgb(182,63,72)"> {{v.foodPrice}}</span>
            </template>
            <!-- 自定义图片  -->
            <template #thumb>
              <van-image fit="cover" :src="v.foodImg"  width="90px"
                         height="85px" />
            </template>
            <!--  自定义原价-->
            <template #origin-price>
              <span style="font-size: 0.9rem">
                  ￥{{v.foodPrice+3}}
              </span>
            </template>
            <!--  自定义数量  -->
            <template #num>
              <span style="display: flex; align-items: center">
                <van-icon v-show="v.quantity!=0"
                          name="clear" size="4.5vw" color="rgb(33, 163, 239)"
                          style="margin-left: 1.8vw"
                          @click="minus(v.foodId)">
                </van-icon>
                <span v-show="v.quantity!=0"
                      style="margin: 0 2.2vw; font-size:1.5vh ">
                  {{ v.quantity }}
                </span>
                <van-icon name="add" size="4.5vw"
                          color="rgb(33, 163, 239)"
                          @click="add(v.foodId)"></van-icon>
              </span>
            </template>
          </van-card>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </van-list>
<!--  底部提交栏  -->
  <van-submit-bar :price=totalPrice button-text="去结算" button-color="rgb(3, 181, 253)" @submit="onSubmit"
                  :disabled="totalNum === 0">
    <template #default>
        <van-icon v-if="totalNum==0" name="shopping-cart" size="10vw" color=gray />
        <van-icon v-else name="shopping-cart" size="10vw" color="#1989fa" :badge=totalNum />
    </template>
    <template #tip>
      <div style="display: flex ; justify-content: center;align-items: center">
        首次光顾减2、满45减1、满65减2、满85减3
      </div>
    </template>
  </van-submit-bar>
<!--  弹出层 -->
  <van-popup
      style="background-color:rgb(245, 245, 245);"
      v-model:show="panelShow"
      round
      position="bottom"
      :style="{ height: '80%' }"
  >
    <OpLoading  :loading="isLoading" type="skeleton">
      <!-- 联系人卡片   -->
      <div class="contact-panel">
        <van-contact-card type="edit" :name=contactName :tel=tel @click="onEdit" >
        </van-contact-card>
      </div>
      <!--    展示地址层 -->
      <van-popup
          v-model:show="panelAddress"
          round
          position="bottom"
          :style="{ height: '80%' }"
      >
        <Address />
      </van-popup>
      <!-- 时间条过渡  -->
      <div style="display: flex;align-items:center;justify-content:center;
      margin: 2vw 5vw;border-radius: 10px;background-color:#fff;height: 6.5vh">
        立即送出<span style="color:rgb(31, 169, 222);margin-left: 3vw">预计{{getTime()}}~{{getTime2()}}送达</span>
      </div>
      <!--食品信息模块-->
      <div style="display:flex;flex-direction:column;justify-content: center;align-items: center">
        <van-card
            style="width: 90%;background-color:#fff;border-radius: 10px"
            class="goods-card"
            v-for="v in CartList" :key="v.cartId"
        >
          <template #title>
            <div style="font-size: 3.5vw;font-weight: bold">
              {{getFoodItem(v.foodId).foodName}}
            </div>
          </template>
          <template #desc>
            <div style="font-style: italic;margin:0.6vh 0">
              {{getFoodItem(v.foodId).foodExplain}}
            </div>
          </template>
          <template #price>
            <span style="font-size:0.8rem;color: rgb(182,63,72)">￥</span>
            <span style="font-size: 2vh;color: rgb(182,63,72)">  {{getFoodItem(v.foodId).foodPrice}}</span>
          </template>
          <template #thumb>
            <van-image fit="cover" :src="getFoodItem(v.foodId).foodImg" />
          </template>
          <template #tags>
            <span style="font-size: 3.5vw;color: gray"> ×{{v.quantity}}</span>
          </template>
        </van-card>
        <!-- 找人付-->
        <van-radio-group v-model="checkedup"  style="width:98% ;margin: 2vw 5vw">
          <van-cell-group inset>
            <van-cell title="找人付" clickable @click="checkedup = '1'">
              <template #icon>
                <van-icon name="cash-back-record" size="2vh" color="rgb(13, 179, 243)" style="margin-top: 0.25vh"/>
              </template>
              <template #label>
                <span>提交订单后，可分享给好友帮你付</span>
              </template>
              <template #right-icon>
                <van-radio name="1" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
        <!-- 支付方式选择-->
        <van-radio-group v-model="checked" style="width:98% ;margin: 2vw 5vw">
          <van-cell-group inset>
            <van-cell title="支付宝" clickable @click="checked = '1'">
              <template #icon>
                <van-icon name="alipay" size="2.5vh" color="rgb(1, 114, 255)" />
              </template>
              <template #right-icon>
                <van-radio name="1" />
              </template>
            </van-cell>
            <van-cell title="微信支付" clickable @click="checked = '2'">
              <template #icon>
                <van-icon name="wechat-pay" size="2.5vh" color="rgb(73, 189, 75)" />
              </template>
              <template #right-icon>
                <van-radio name="2" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>

      </div>
      <!--底部提交栏-->
      <van-submit-bar :price=totalPrice button-text="提交订单" button-color="rgb(3, 181, 253)"
                      :disabled="checked ===0"
                      @submit="onSubmitOrder" />
    </OpLoading>
  </van-popup>

</template>

<script setup lang="ts">
import {onMounted, ref,computed} from 'vue'
import {AddShop, RemoveShop, reqFoodInfo, reqShopInfo, UpdateShop} from "../../../api/shop";
import type {CartListResponseData, FoodInfo, ShopInfo, ShopQuery, ShopUpdateData} from "@/api/shop/type.ts";
import OpLoading from "@/components/OpLoading.vue";
import useUserStore from "@/store/modules/user.ts";
import {useRouter} from "vue-router";
import {showNotify, showToast} from "vant";
import Address from "@/views/address/index.vue"
import {reqAddressUser} from "@/api/address";
import {GET_USERID, GET_USERNAME} from "@/utils/localStore.ts";
import type {AddressUserData} from "@/api/address/type.ts";
import {RemoveFilled} from "@element-plus/icons-vue";
import type {orderForm} from "@/api/order/type.ts";
import {createOrder} from "@/api/order";
//标签页当前激活项的索引
const activeTab=ref(0);
//loading效果
const loading = ref(false);
const finished = ref(false);
//pinia仓库
let useStore=useUserStore();
//获取路由器
let $router=useRouter();
// 存储食品数据
const FoodList:any=ref([]);
//底部弹出框
const panelShow=ref(false);
const panelAddress=ref(false);
const isLoading=ref<boolean>(true);
//获取用户名称
const contactName:any=GET_USERNAME();
const tel=ref();
//接受父组件的传值
interface IProps{
  data:number
}
const props=defineProps<IProps>();
//食品弹窗
const FOOD_TAB=[
  {title:'新客专享'},
  {title:'专属福利,超值推荐'}
];
//侧边栏
// 侧边栏数据
const sidebarItems = [
  { title: '热销' },
  { title: '限时优惠' },
  { title: '新品尝鲜' },
  { title: '网红打卡' },
  { title: '夏季缤纷' },
  { title: '爆款热卖' },
  { title: '必点套餐' },
  { title: '多人特惠' },
  { title: '美味小食' },
];
// 当前选中的侧边栏索引
const activeIndex = ref(0);

// 获取右侧列表的 DOM 元素
const listRight = ref<HTMLElement | null>(null);
// 侧边栏点击事件
const onSidebarChange = (index: number) => {
  activeIndex.value = index;
  // 滚动到对应的分类
  const targetElement = document.getElementById(`category-${index}`);
  if (targetElement && listRight.value) {
    targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};
// 滚动事件
const onScroll = () => {
  if (!listRight.value) return;

  // 获取所有分类的 DOM 元素
  const categories = sidebarItems.map((_, index) =>
      document.getElementById(`category-${index}`)
  );

  // 计算当前可见的分类
  for (let i = 0; i < categories.length; i++) {
    const category = categories[i];
    if (category) {
      const rect = category.getBoundingClientRect();
      if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
        activeIndex.value = i;
        break;
      }
    }
  }
};
//panel栏
const anchors = [
  Math.round(0.85 * window.innerHeight),
];
const height = ref(anchors[0]);

//购物车逻辑
const shopQuery:ShopQuery=({userId:'',businessId:0});
const CartList:any=ref([]);
const shopInfo:ShopInfo=({userId:'',
  businessId:0,
  foodId:0});
const shopAddInfo:ShopUpdateData=({userId:'',
  businessId:0,
  foodId:0,
  quantity:0});
//单选框
const checkedup:any=ref(0);
//支付方式选择
const checked:any=ref(0);

//获取食品信息
const onLoad=async ()=>{
  let result=await reqFoodInfo(props.data);
  if(result.code==1){
    // 数组赋值 并添加新的quantity属性
    const resultCurrent = result.data.map(item => ({
      ...item,
      quantity: 0 // 初始化 quantity 为 0
    }));
    FoodList.value = resultCurrent;
    // 加载状态结束
    loading.value = false;
    // 数据全部加载完成
    if (result.data.length >= 9) {
      finished.value = true;
    }
  }
  // console.log(FoodList.value);
}
const getAddressInfo=async()=>{
  // console.log(contactName);
  let result:AddressUserData=await reqAddressUser(contactName);
  if(result.code==1){
    tel.value=result.data.contactTel;
    //存入daId
    order.daId=result.data.daId;
  }
  // console.log(tel.value)
}
//挂载时请求
onMounted(()=>{
  onLoad();
  if (listRight.value) {
    listRight.value.addEventListener('scroll', onScroll);
  }
  //每次加载时删除清空购物车
  removeALL();
})

const add=(foodId:number)=>{
  //登录校验
  //获取token 等信息
  let token=useStore.token;
  if(!token){
    showNotify({ type: 'danger', message: '未登录' });
    //跳转到登录页面
    $router.push('/login');
  }
  let businessId=props.data;
  let userId=GET_USERID() as string;

  shopInfo.userId=userId;
  shopInfo.foodId=foodId;
  shopInfo.businessId=businessId;
  if(!token){
    showNotify({ type: 'danger', message: '未登录' });
    //跳转到登录页面
    $router.push('/login');
  }
 //检查当前quantity是否为0
  const index = FoodList.value.findIndex((item: any) => item.foodId === foodId);
  let quantity=FoodList.value[index].quantity;
  if (quantity === 0) {
      // 新增
      AddShop(shopInfo);
      quantity++;
  }else{
    // 更新
    quantity++;
    shopAddInfo.userId=userId;
    shopAddInfo.businessId=businessId;
    shopAddInfo.foodId=foodId;
    shopAddInfo.quantity=quantity;
    UpdateShop(shopAddInfo);
  }
  // 写回
  FoodList.value[index].quantity=quantity;
}
const minus=(foodId:number)=>{
  //登录校验
  //获取token 等信息
  let businessId=props.data;
  let userId=GET_USERID() as string;
  let token=useStore.token;
  shopInfo.userId=userId;
  shopInfo.foodId=foodId;
  shopInfo.businessId=businessId;
  if(!token){
    showNotify({ type: 'danger', message: '未登录' });
    //跳转到登录页面
    $router.push('/login');
  }
  //检查当前quantity是否为0
  const index = FoodList.value.findIndex((item:any) => item.foodId === foodId);
  let quantity=FoodList.value[index].quantity;
  if(quantity>1){
    // 更新
    quantity--;
    shopAddInfo.userId=userId;
    shopAddInfo.businessId=businessId;
    shopAddInfo.foodId=foodId;
    shopAddInfo.quantity=quantity;
    UpdateShop(shopAddInfo);
  }else{
    //删除
    RemoveShop(shopInfo);
    quantity=0;
  }
  // 写回
  FoodList.value[index].quantity=quantity;
}
// 清空购物车
const removeALL=async ()=>{
  let businessId=props.data;
  shopInfo.userId=GET_USERID() as string;
  shopInfo.foodId=-1;
  shopInfo.businessId=businessId;
  await RemoveShop(shopInfo);
}
// 食品总价 计算属性
const totalPrice = computed(() => {
  return FoodList.value.reduce((total:any, food:any) => total + food.foodPrice * food.quantity, 0)*100;
});

// 食品总数量
const totalNum = computed(() => {
  return FoodList.value.reduce((total:any, food:any) => total + food.quantity, 0);
});
//去结算
const onSubmit=()=>{
  //获取token
  let token=useStore.token;
  if(token){
    panelShow.value=true;
    //获取地址信息
    getAddressInfo();
    //查询购物车信息
    getCartInfo();
    //加载效果结束
    isLoading.value=false;
  }else{
    showNotify({ type: 'danger', message: '未登录' });
    //跳转到登录页面
    $router.push('/login');
  }
}
//查询购物车信息
const getCartInfo=async ()=>{
  shopQuery.userId=GET_USERID() as string;
  shopQuery.businessId=props.data;
  // console.log(shopQuery.businessId);
  let result=await reqShopInfo(shopQuery);
  if(result.code==1){
    CartList.value=result.data;
  }
  // console.log(CartList.value);
}

const getFoodItem=(foodId:number)=>{
  return FoodList.value.find((f:FoodInfo) => f.foodId === foodId);
}
//跳转收货地址
const onEdit=()=>{
  panelAddress.value=true;
}
//获取时间
const getTime=()=>{
  let message='';
  //内置函数调用
  let hours=new Date().getHours();
  let minus=new Date().getMinutes();
  message=hours+':'+minus;
  return message;
}

const getTime2=()=>{
  let message = '';
  // 内置函数调用
  let hours = new Date().getHours();
  let minutes = new Date().getMinutes();
  let newMinutes = minutes + 10;
  // 处理分钟数超过59的情况
  if (newMinutes >= 60) {
    hours = (hours + 1) % 24; // 小时数加1，并且确保在0-23之间
    newMinutes = newMinutes - 60; // 分钟数减去60
  }
  message = hours + ':' + newMinutes.toString().padStart(2, '0'); // 确保分钟数是两位数
  return message;
}
//提交订单

//提交订单实体
const order:orderForm=({ userId:'',
  businessId:0,
  daId:0,
  orderTotal:0})
const onSubmitOrder=async ()=>{
  order.businessId=props.data;
  order.userId=GET_USERID() as string;
  order.orderTotal=(totalPrice.value)/100;
  let result:any=await createOrder(order);
  if(result.code==1){
    showToast('提交成功');
    // 延迟跳转
    setTimeout(() => {
      $router.push('/shopping');
    }, 1000);
  }
  // console.log(result);

}
</script>

<style scoped>
.home{
  display: flex;
  width: 100%;
  flex-direction: row;
  height: 100vh;
}
.home .list-left{
  flex:2;
  display:flex;
  overflow-y: auto;
  top: 0;
  bottom: 0;
  height: 100%;
}
.home .list-right{
  display: flex;
  flex-direction: column;
  flex:8;
  overflow-y: auto;
  height: 100%;
}
</style>